package spring.boot.shiro.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import spring.boot.shiro.entity.Permission;
import spring.boot.shiro.entity.User;
import spring.boot.shiro.service.PermissionService;
import spring.boot.shiro.service.UserService;

import java.util.*;

/**
 * Created by Administrator on 2018/6/10.
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("============授权===============");
        Session session = SecurityUtils.getSubject().getSession();
        //查询用户的权限
        Permission permission = (Permission) session.getAttribute(CacheInfo.SESSION_USER_PERMISSION);
        System.out.println(permission.getUrl()+"@@@@@@@@@@@@@@@@@@@@");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        List<String> list = new ArrayList<>();
        for (String str:permission.getUrl().split(",")){
            list.add(str);
        }
        authorizationInfo.addStringPermissions(list);
        return authorizationInfo;
    }


    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("=============认证==============");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String name = token.getUsername();
        User user = userService.findByName(name);
        Session session = SecurityUtils.getSubject().getSession();
        Permission permission = permissionService.findByName(user.getRole());
        System.out.println(permission.getUrl()+"@@@@@@@@@@@@@@@@@@@@");
        session.setAttribute(CacheInfo.SESSION_USER_PERMISSION,permission);
        //设置session超时时间，默认超时时间为30分钟
        session.setTimeout(1800000L);
        return new SimpleAuthenticationInfo(user,user.getPasswd(),this.getClass().getName());
    }
}
